<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sw_perusahaan extends MY_Controller {
	
	function __construct()
	{
		parent::__construct(); 
		
		// Uses Model
		$this->load->model('sw_perusahaan_model', 'Perusahaan');
		$this->load->model('combo_model', 'Combo');
		
		// Secure Page With Session
		$this->secure_session();
	}
	
	function index(){
		// Display Index
		$data['title'] = $this->session_menu_label;
		
		viewByTemplate('sw_perusahaan/index', $data, 'grid');
	}
	
	function getdata()
	{
		// Ajax Response For Datagrid
		echo $this->Perusahaan->GetJSON();
	}
	
	function create()
	{
		// Display Form Create
		$data['title'] = "Tambah Data Perusahaan";
		$data['data'] = NULL;
		
		// Define Combo Data
		$data['arr_province']	= $this->Combo->SWProvince();
		$data['arr_country']	= $this->Combo->SWCountryAll();
		
		$data['mode'] = "create";
		viewByTemplate('sw_perusahaan/form', $data, 'form');
	}

	function edit()
	{
		// Display Form Edit
		$data['title'] = "Ubah Data Perusahaan";
		$data['data'] = $this->Perusahaan->GetSingleView(get('id_perusahaan'));
		
		// Define Combo Data
		$data['arr_province']	= $this->Combo->SWProvince();
		$data['arr_country']	= $this->Combo->SWCountryAll();
		
		$data['mode'] = "edit";
		viewByTemplate('sw_perusahaan/form', $data, 'form');
	}
	
	private function validation()
	{
		$error = new ErrorList();

		// Get Error Template
		$tpl_empty		= $this->MessageTemplate("ER001");
		$tpl_duplicate	= $this->MessageTemplate("ER002");


		// Validation
		if (post("kode_perusahaan") == '') {
			$error->Add("kode_perusahaan", "kode_perusahaan", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT COUNT(1) FROM SW_PERUSAHAAN WHERE UPPER(kode_perusahaan) = '".@strtoupper(@trim(post("kode_perusahaan")))."'")) > 0) {
			$error->Add("kode_perusahaan", "kode_perusahaan", $tpl_duplicate);
		} else if (post("mode") == "edit" && intval($this->get_data("SELECT COUNT(1) FROM SW_PERUSAHAAN WHERE UPPER(kode_perusahaan) = '".@strtoupper(@trim(post("kode_perusahaan")))."' AND UPPER(id_perusahaan) <> '".@strtoupper(@trim(post('id_perusahaan')))."'")) > 0) {
			$error->Add("kode_perusahaan", "kode_perusahaan", $tpl_duplicate);
		}
		
		if (post("nama_perusahaan") == '') {
			$error->Add("nama_perusahaan", "nama_perusahaan", $tpl_empty);
		} else if (post("mode") == "create" && intval($this->get_data("SELECT COUNT(1) FROM SW_PERUSAHAAN WHERE UPPER(nama_perusahaan) = '".@strtoupper(@trim(post("nama_perusahaan")))."'")) > 0) {
			$error->Add("nama_perusahaan", "nama_perusahaan", $tpl_duplicate);
		} else if (post("mode") == "edit" && intval($this->get_data("SELECT COUNT(1) FROM SW_PERUSAHAAN WHERE UPPER(nama_perusahaan) = '".@strtoupper(@trim(post("nama_perusahaan")))."' AND UPPER(id_perusahaan) <> '".@strtoupper(@trim(post('id_perusahaan')))."'")) > 0) {
			$error->Add("nama_perusahaan", "nama_perusahaan", $tpl_duplicate);
		}
		
		return $error;
	}
	
	function ajax_post()
	{
		// Ajax Response For Submit Form
		$is_error = 0;
		$ls_response = "";
		$ls_genid = "";
		
		// Get Error Template
		$tpl_insert_success = $this->MessageTemplate("CS001");
		$tpl_update_success = $this->MessageTemplate("CS002");
		
		$error = $this->validation();
		try
		{
			if (count( $error->Get() ) > 0) { $is_error = 1; }
			else
			{
				// Fill Post Data Array
				$data	= post_by_key(array('id_perusahaan','kode_perusahaan','nama_perusahaan','nama_pendek',
											'address','rt','rw','village','subdistrict','city_code','province_code','country_code',
											'zipcode','phone','fax','email','website','tgl_registrasi','tgl_akhir','st_aktif'));
				
				// Set Primary Key Variable
				$data['id_perusahaan']	= @strtoupper(@trim(post("id_perusahaan")));
				$id_perusahaan			= $data['id_perusahaan'];
				
				// Set Date Format
				$data['tgl_registrasi']	= ($data['tgl_registrasi'] == '' ? NULL : date_format3($data['tgl_registrasi'], 'YYYY-MM-DD'));
				$data['tgl_akhir']		= ($data['tgl_akhir'] == '' ? NULL : date_format3($data['tgl_akhir'], 'YYYY-MM-DD'));
				
				if (post("mode") == "create")
				{
					$ls_genid				= 'COM'.str_pad($this->get_data("SELECT NVL((SELECT MAX(SUBSTR(id_perusahaan,4,5)) FROM SW_PERUSAHAAN),0)+1 NoUrut FROM DUAL"),3,'0',STR_PAD_LEFT);
					$data['id_perusahaan']	= $ls_genid;
					$data['create_date']	= NOW;
					$data['create_user']	= USERID;
					
					$this->Perusahaan->Add($data);
					
					$ls_response = $tpl_insert_success['message_id'];
				}
				else if (post("mode") == "edit")
				{
					unset($data['id_perusahaan']);
					
					$data['modify_date']	= NOW;
					$data['modify_user']	= USERID;
					
					$this->Perusahaan->Update(	$data, 
												array('id_perusahaan'	=> $id_perusahaan));

					$ls_response = $tpl_update_success['message_id'];
				}
			}
		} catch(Exception $e) {
			$is_error = 1; $ls_response = $e->getMessage();
		}
		
		echo $this->PostResponse(json_encode(array(	'is_error'	=> $is_error,
													'fields'	=> $error->GetDictionary(),
													'msg'		=> $ls_response,
													'genid'		=> $ls_genid,
													'form_sender'=> post("form_sender"))
								));
	}

	function ajax_delete()
	{
		$ls_result	= "";
		$id_perusahaan	= get('id_perusahaan');
		
		if ($id_perusahaan != "")
		{
			// Delete Single
			$arr_rule	= array('id_perusahaan' => $id_perusahaan);
			$ls_result = $this->Perusahaan->DeleteSingle($arr_rule);
		}
		else
		{
			$num_row = intval($this->data['num_row']['deleted']);
			
			for ($i = 0; $i < $num_row; $i++)
			{
				$row	= $this->data['deleted'][$i];
				
				$arr_rule	= array('id_perusahaan' => $row['id_perusahaan']);
				$ls_result .= $this->Perusahaan->DeleteSingle($arr_rule);
			}
		}
		
		echo $ls_result;
	}
	
	function download(){
		$filename			= APPPATH . '/file/cache/' . _SESSID.'.xls';
		@unlink($filename);
		$this->load->helper('file');
		
		$arr_alphabet	= array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EL', 'EK', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ');
		
		$ls_sql	= "	SELECT	A.ID_PERUSAHAAN, A.KODE_PERUSAHAAN, A.NAMA_PERUSAHAAN, A.NAMA_PENDEK, A.ADDRESS ALAMAT, A.RT, A.RW, A.VILLAGE KELURAHAN, A.SUBDISTRICT KECAMATAN, B.CITY_NAME KOTA, C.PROVINCE_NAME PROVINSI, D.COUNTRY_CODE NEGARA, A.ZIPCODE KODEPOS, A.PHONE, A.FAX, A.EMAIL, A.WEBSITE, A.ST_AKTIF
					FROM	SW_PERUSAHAAN A
							LEFT JOIN SW_CITY B ON A.CITY_CODE=B.CITY_CODE
							LEFT JOIN SW_PROVINCE C ON C.PROVINCE_CODE=A.PROVINCE_CODE
							LEFT JOIN SW_COUNTRY D ON D.COUNTRY_CODE=A.COUNTRY_CODE
					ORDER BY A.KODE_PERUSAHAAN";
						
						
		$result			= $this -> db -> query($ls_sql);
		$arr_data		= $result->result_array();
		
		if(count($arr_data)==0){ echo 'Data Empty..'; die; }
		
		require_once APPPATH . "third_party/PHPExcel.php";
		require_once APPPATH . "third_party/PHPExcel/IOFactory.php";
		
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();

		// Set properties
		$objPHPExcel->getProperties()->setCreator("Primkokas")
									 ->setLastModifiedBy("Primkokas")
									 ->setTitle("Office 2007 XLSX Import Data Document")
									 ->setSubject("Office 2007 XLSX Import Data Document")
									 ->setDescription("Import data document for Office 2007 XLSX, generated using PHP classes.")
									 ->setKeywords("office 2007 openxml php")
									 ->setCategory("Import result file");
		
		@set_time_limit(0);                   // ignore php timeout
		//@ignore_user_abort(true);             // keep on going even if user pulls the plug*
		
		$styleH1 = array('font' => array('bold' => true, 'size' => 18));
		$styleH2 = array('font' => array('bold' => true));
		
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'List Perusahaan');
		$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleH1);
		
		$ln_index	= 2;
		for($i=0,$max_i=count($arr_data); $i<$max_i; $i++){
			$row	= $arr_data[$i];
			if($i==0){ $arr_key	= array_keys($row); }
				
			// Add some data, we will use printing features
			// Header
			if($i==0){
				for($j=0, $max_j=count($arr_key); $j<$max_j; $j++){
					$field_name	= $arr_key[$j];
					
					$ls_coordinate	= $arr_alphabet[$j] . ($ln_index);
					$objPHPExcel->getActiveSheet()->setCellValue($ls_coordinate, $field_name);
					$objPHPExcel->getActiveSheet()->getStyle($ls_coordinate)->applyFromArray($styleH2);
				}
				$ln_index++;
			}
			
			// Data
			for($j=0, $max_j=count($arr_key); $j<$max_j; $j++){
				$field_name	= $arr_key[$j];
				$value		= $row[$field_name];
				
				$value	= str_replace("\t", '\t', $value);
				$value	= str_replace("\n",'\n', $value);
				$value	= str_replace(chr(10),'\n', $value);
				$value	= str_replace(chr(13),'\n', $value);
				if($j==4){ $value = strip_tags($value); }
				
				$ls_coordinate	= $arr_alphabet[$j] . ($ln_index);
				//echo $ls_coordinate.' ; ';
				$objPHPExcel->getActiveSheet()->setCellValue($ls_coordinate, $value);
			}
			$ln_index++;
		}
		
		
		// ------ >> Save EXCEL
		if(count($arr_data)>0){
			// Rename sheet
			//echo date('H:i:s') . " Rename sheet\n";
			$objPHPExcel->getActiveSheet()->setTitle('Sheet 1');
			
			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			$objPHPExcel->setActiveSheetIndex(0);

			// Save Excel 2007 file
			//echo date('H:i:s') . " Write to Excel2007 format\n";
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save($filename);

		}
	}
}
?>